package plugins.schoolcard;

import com.alibaba.druid.util.StringUtils;
import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.form.control.events.ItemClickEvent;
import kd.sdk.plugin.Plugin;

import java.util.Calendar;
import java.util.Date;
import java.util.EventObject;

/**
 * 单据界面插件
 */
public class TimeLock extends AbstractBillPlugIn implements Plugin {
    private static final String TIME_FIELD = "dcb4_time"; // 时间字段标识
    private static final String DATE_FIELD = "dcb4_date"; // 新增日期字段标识
    private static final String ACTION_BUTTON = "dcb4_lock"; // 按钮标识

    @Override
    public void afterBindData(EventObject e) {
        // 页面加载时锁定时间字段和日期字段
        this.getView().setEnable(false, TIME_FIELD);
        this.getView().setEnable(false, DATE_FIELD);
    }

    @Override
    public void registerListener(EventObject e) {
        // 注册工具栏监听
        this.addItemClickListeners("tbmain", "advcontoolbarap");
        super.registerListener(e);
    }

    @Override
    public void itemClick(ItemClickEvent evt) {
        String itemKey = evt.getItemKey();
        if (StringUtils.equalsIgnoreCase(itemKey, ACTION_BUTTON)) {
            // 临时解锁字段
            this.getView().setEnable(true, TIME_FIELD);
            this.getView().setEnable(true, DATE_FIELD);

            // 获取当前系统时间
            Calendar calendar = Calendar.getInstance();
            Date now = calendar.getTime();

            // 1. 写入时间字段（计算从当天零点到当前时间的总秒数）
            int hour = calendar.get(Calendar.HOUR_OF_DAY);
            int minute = calendar.get(Calendar.MINUTE);
            int second = calendar.get(Calendar.SECOND);
            int totalSeconds = hour * 3600 + minute * 60 + second;
            this.getModel().setValue(TIME_FIELD, totalSeconds);

            // 2. 写入日期字段（只保留年月日部分）
            Calendar dateOnly = Calendar.getInstance();
            dateOnly.setTime(now);
            dateOnly.set(Calendar.HOUR_OF_DAY, 0);
            dateOnly.set(Calendar.MINUTE, 0);
            dateOnly.set(Calendar.SECOND, 0);
            dateOnly.set(Calendar.MILLISECOND, 0);
            this.getModel().setValue(DATE_FIELD, dateOnly.getTime());

            // 立即锁定字段
            this.getView().setEnable(false, TIME_FIELD);
            this.getView().setEnable(false, DATE_FIELD);

            // 刷新界面显示
            this.getView().updateView(TIME_FIELD);
            this.getView().updateView(DATE_FIELD);
        }
        super.itemClick(evt);
    }
}